package com.itheima.d2_reflect_test;

import org.junit.Test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/*
    对象框架
    目标：保存任意对象的字段和其数据到文件中去
 */
public class ObjectFrame {

    public static void saveObj(Object obj) throws Exception{
            //1把数据保存到文件
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("user.txt", true));
        //2获取Class对象
        Class c = obj.getClass();
        bufferedWriter.write("============================="+c.getSimpleName()+"============================");
        bufferedWriter.newLine();
        bufferedWriter.flush();
        Field[] declaredMethod = c.getDeclaredFields();
        for (Field method : declaredMethod) {
            method.setAccessible(true);
            String name = method.getName();
            Object value = method.get(obj);
            bufferedWriter.write(name + "=" + value);
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }
        bufferedWriter.close();
    }
}
